﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EV.EventBus;
using ZoneLine.Models;
using Common;

namespace ZoneLine.Stations
{
    /// <summary>
    /// 衬套弹簧
    /// </summary>
    /// <remarks>
    /// <para>弹簧测高工位</para>
    /// <para>StationCode：OP570    IP：192.168.10.75</para>
    /// </remarks>
    public class QOP010Station : WorkStationDBase
    {
        public QOP010Station()
        {
        }

        public string WorkDirectionAddr { get; set; }
        public string CurrentProductType { get; set; }

        public void Init(string ip, int port = 102, string startAddr = "DB55.0", string endUploadCodeAddr = "DB55.18.1", string endUploadDataAddr = "DB55.18.2", string allowWorkAddr = "DB55.20")
        {
            Ip = ip;
            Port = port;
            _startAddr = startAddr;
            StationCode = "OP570";
            EndUpLoadCodeAddr = endUploadCodeAddr;
            EndUpLoadDataAddr = endUploadDataAddr;
            AllowWorkAddr = allowWorkAddr;
            HeartToPlcAddr = "DB1001.0";
            WorkDirectionAddr = "DB1001.14";
            CurrentProductType = "DB1001.2168";

            _readLength = 1036;

            StationRecordData = new QOP010StationResult();

            //TaskMaster.Default.AddCycleTask(nameof(QOP010Station), 1, () =>
            //{
            //    #region 不在需要下发了，下发配方的时候下位机自行判断
            //    ////var value = (short)Cache.WorkDirection;
            //    ////WriteData(WorkDirectionAddr, value);
            //    ////_client?.Write(CurrentProductType, Cache.CurrentProductType);
            //    #endregion
            //}, false, EV.EventBus.CycleTask.TimeBaseEnum._1S);

            _logUiChannel = CurrentStationName + "uilog";

            base.InitReSetAddr();
        }

        private QOP010StationResult _stationRecordData;

        public QOP010StationResult StationRecordData
        {
            get { return _stationRecordData; }
            set => SetProperty(ref _stationRecordData, value);
        }

        protected override void DealData(byte[] content)
        {
            StationRecordData.AbsScanCode = GetPlcString(content, 280);
            StationRecordData.BushScanCode = GetPlcString(content, 322);
            StationRecordData.PartType = GetPlcString(content, 1002);
            StationRecordData.Result = _client.ByteTransform.TransInt16(content, 1000).ToString().Equals("1") ? "OK" : "NG";
            StationRecordData.PressPosition = _client.ByteTransform.TransSingle(content, 1024);
            StationRecordData.PressForce = _client.ByteTransform.TransSingle(content, 1028);
            StationRecordData.CycleTime = _client.ByteTransform.TransSingle(content, 1032);
        }

        string _absScanCodeTemp = "";
        protected override void DealWithSignal(string name)
        {
            if (name == nameof(StartUploadCode))
            {
                //todo 上传了条码 这时候验证是否要工作
                if (StartUploadCode == false)
                {
                    LogWithUi(_logUiChannel, $"在{CurrentStationName}收到上传条码命令变为false", StationRecordData.AbsScanCode);
                    WriteData(EndUpLoadCodeAddr, 0, StationRecordData.AbsScanCode);
                    WriteData(AllowWorkAddr, 0, StationRecordData.AbsScanCode);
                    LogWithUi(_logUiChannel, $"在{CurrentStationName}复位工作控制指令和复位上传条码完成指令", StationRecordData.AbsScanCode);
                    return;
                }
                else
                {
                    _absScanCodeTemp = StationRecordData.AbsScanCode;
                    LogWithUi(_logUiChannel, $"在{CurrentStationName}收到上传条码信息命令", StationRecordData.AbsScanCode);
                    LogWithUi(_logUiChannel, $"在{CurrentStationName}工位结论验证,条码信息是{StationRecordData.AbsScanCode}", StationRecordData.AbsScanCode);
                    var validataRlt = Validata(CurrentStationName, StationRecordData.AbsScanCode);
                    LogWithUi(_logUiChannel, $"在{CurrentStationName}工位的验证结果是{validataRlt}", StationRecordData.AbsScanCode);
                    var writeRlt = WriteWorkActionToPlc(AllowWorkAddr, validataRlt, StationRecordData.AbsScanCode, true);
                    LogWithUi(_logUiChannel, $"在{CurrentStationName}工位向下位机下发消息，下发{writeRlt}", StationRecordData.AbsScanCode);
                    return;
                }
            }

            if (name == nameof(StartUploadData))
            {
                if (StartUploadData)
                {
                    //todo 上传数据 这时候将数据记录到数据库中
                    LogWithUi(_logUiChannel, $"在{CurrentStationName}收到上传记录数据命令", StationRecordData.AbsScanCode);

                    if (_absScanCodeTemp == StationRecordData.AbsScanCode)
                    {
                        var rlt = RecordData();
                        WriteData(EndUpLoadDataAddr, (short)rlt, StationRecordData.AbsScanCode, true);
                        LogWithUi(_logUiChannel, $"在{CurrentStationName}数据记录,rlt={rlt}", StationRecordData.AbsScanCode);
                    }
                    else
                    {
                        LogWithUi(_logUiChannel, $"在{CurrentStationName}数据记录失败,条码信息不一致,temp:{_absScanCodeTemp} current:{StationRecordData.AbsScanCode}", StationRecordData.AbsScanCode);
                    }
                }
                else
                {
                    LogWithUi(_logUiChannel, $"在{CurrentStationName}收到上传记录数据命令变为false", StationRecordData.AbsScanCode);

                    WriteData(EndUpLoadDataAddr, 0, StationRecordData.AbsScanCode, true);
                    LogWithUi(_logUiChannel, $"在{CurrentStationName}数据记录,clear", StationRecordData.AbsScanCode);
                    _absScanCodeTemp = "";
                }
            }
        }

        protected override int RecordData()
        {
            var result = new QOP010StationResult()
            {
                AbsScanCode = StationRecordData.AbsScanCode,
                BushScanCode = StationRecordData.BushScanCode,
                StationCode = this.StationCode,
                PartType = StationRecordData.PartType,
                Result = StationRecordData.Result,
                PressPosition = StationRecordData.PressPosition,
                PressForce = StationRecordData.PressForce,
                CycleTime = StationRecordData.CycleTime,
            };
            var writeRlt = false;
            if (_dal.CheckExist<QOP010StationResult>(p => p.AbsScanCode == result.AbsScanCode))
            {
                var beforeRlt = _dal.GetModel<QOP010StationResult>(p => p.AbsScanCode == result.AbsScanCode);
                result.Id = beforeRlt.Id;
                writeRlt = _dal.UpdateModelSuper<QOP010StationResult>(p => p.AbsScanCode == result.AbsScanCode, result);
            }
            else
            {
                writeRlt = _dal.AddModel(result);
            }
            return writeRlt ? 1 : 2;
        }
    }
}